package com.agent.generator.service;

import com.agent.credit.api.feign.CreditFeignClient;
import com.agent.generator.dto.TaskDetailsDTO;
import com.agent.generator.rabbitmq.AiGenerateProducer;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.agent.common.constant.CommonConstants;
import com.agent.common.exception.BusinessException;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.CreditCalculator;
import com.agent.common.utils.IdGenerator;
import com.agent.generator.entity.GeneratedTask;
import com.agent.generator.mapper.GeneratedTaskMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 任务管理服务
 * @author Jeff_Wan
 * @description 处理任务的创建、状态管理和积分扣除
 */
@Service
@RequiredArgsConstructor
public class GeneratedTaskService extends ServiceImpl<GeneratedTaskMapper, GeneratedTask> {
    private final IdGenerator idGenerator = IdGenerator.getInstance();
    private final GeneratedTaskMapper generatedTaskMapper;
    private final FileStorageService fileStorageService;
    private final CreditFeignClient creditFeignClient;
    private final AiGenerateProducer aiGenerateProducer;
    private final GeneratedContentService generatedContentService;

    /**
     * 创建视频生成任务
     * @param userId 用户ID
     * @param model 模型名称
     * @param prompt 提示词
     * @param imageFile 输入图片
     * @param duration 视频时长
     * @param resolution 分辨率
     * @param aspectRatio 画面比例
     * @return 任务ID
     */
    @Transactional
    public Long createVideoTask(Long userId, String model, String prompt, MultipartFile imageFile,
                                Integer duration, String resolution, String aspectRatio) {
        // 验证模型是否支持视频生成
        validateVideoModel(model);

        // 计算所需积分
        int creditsRequired = CreditCalculator.calculateVideoCredits(model, duration, resolution);

        // 扣除积分（通过Feign调用积分服务）
        creditFeignClient.deductCredits(userId, creditsRequired);

        // 保存输入图片（如果有）
        String inputImagePath = null;
        if (imageFile != null && !imageFile.isEmpty()) {
            inputImagePath = fileStorageService.storeFile(imageFile, userId, "input");
        }

        // 创建任务记录
        GeneratedTask generatedTask = new GeneratedTask();
        generatedTask.setId(idGenerator.nextId());
        generatedTask.setUserId(userId);
        generatedTask.setTaskType(CommonConstants.ASSET_VIDEO);
        generatedTask.setModel(model);
        generatedTask.setPrompt(prompt);
        generatedTask.setInputImagePath(inputImagePath);
        generatedTask.setStatus(CommonConstants.TASK_PENDING);
        generatedTask.setCreditsUsed(creditsRequired);
        generatedTask.setDuration(duration);
        generatedTask.setResolution(resolution);
        generatedTask.setAspectRatio(aspectRatio);

        generatedTaskMapper.insert(generatedTask);

        // 发送任务到消息队列
        aiGenerateProducer.sendTaskMessage(generatedTask.getId());

        return generatedTask.getId();
    }

    /**
     * 创建图片生成任务
     *
     * @param userId      用户ID
     * @param model       模型名称
     * @param prompt      提示词
     * @param imageFile   输入图片文件
     * @param aspectRatio 比例
     * @param quantity    生成数量
     * @return 任务ID
     */
    @Transactional
    public Long createImageTask(Long userId, String model, String prompt, MultipartFile imageFile,
                                String aspectRatio, Integer quantity) {
        // 验证模型是否支持图片生成
        validateImageModel(model);

        // 计算所需积分
        int creditsRequired = CreditCalculator.calculateImageCredits(model, quantity);

        // 扣除积分（通过Feign调用积分服务）
        creditFeignClient.deductCredits(userId, creditsRequired);

        // 保存输入图片（如果有）
        String inputImagePath = null;
        if (imageFile != null && !imageFile.isEmpty()) {
            inputImagePath = fileStorageService.storeFile(imageFile, userId, "input");
        }

        // 创建任务记录
        GeneratedTask generatedTask = new GeneratedTask();
        generatedTask.setId(idGenerator.nextId());
        generatedTask.setUserId(userId);
        generatedTask.setTaskType(CommonConstants.ASSET_IMAGE);
        generatedTask.setModel(model);
        generatedTask.setPrompt(prompt);
        generatedTask.setInputImagePath(inputImagePath);
        generatedTask.setStatus(CommonConstants.TASK_PENDING);
        generatedTask.setCreditsUsed(creditsRequired);
        generatedTask.setAspectRatio(aspectRatio);
        generatedTask.setQuantity(quantity);

        generatedTaskMapper.insert(generatedTask);

        // 发送任务到消息队列
        aiGenerateProducer.sendTaskMessage(generatedTask.getId());

        return generatedTask.getId();
    }

    /**
     * 更新任务状态
     *
     * @param taskId        任务ID
     * @param status        新状态
     * @param outputPath    输出路径
     * @param failureReason 失败原因
     */
    @Transactional
    public void updateTaskStatus(Long taskId, String status, String outputPath, String failureReason) {
        GeneratedTask generatedTask = generatedTaskMapper.selectById(taskId);
        if (generatedTask == null) {
            throw new BusinessException(ResultCode.TASK_NOT_FOUND);
        }

        generatedTask.setStatus(status);
        if (outputPath != null) {
            generatedTask.setOutputPath(outputPath);
        }
        if (failureReason != null) {
            generatedTask.setFailureReason(failureReason);
        }

        generatedTaskMapper.updateById(generatedTask);

        // 如果任务失败，退还积分
        if (CommonConstants.TASK_FAILED.equals(status)) {
            creditFeignClient.refundCredits(generatedTask.getUserId(), generatedTask.getCreditsUsed());
        }
    }

    private void validateVideoModel(String model) {
        if (!CommonConstants.MODEL_SEEDANCE_LITE.equals(model) &&
                !CommonConstants.MODEL_SEEDANCE_PRO.equals(model) &&
                !CommonConstants.MODEL_VEO_BASIC.equals(model) &&
                !CommonConstants.MODEL_VEO_PREMIUM.equals(model)) {
            throw new BusinessException(ResultCode.MODEL_NOT_SUPPORTED, "Unsupported video model: " + model);
        }
    }

    private void validateImageModel(String model) {
        if (!CommonConstants.MODEL_GPT_IMAGE.equals(model) &&
                !CommonConstants.MODEL_FLUX_PRO.equals(model)) {
            throw new BusinessException(ResultCode.MODEL_NOT_SUPPORTED, "Unsupported image model: " + model);
        }
    }

    /**
     * 根据任务ID获取任务对象
     *
     * @param taskId 任务ID
     * @return 任务对象
     */
    public GeneratedTask getTaskById(Long taskId) {
        GeneratedTask generatedTask = generatedTaskMapper.selectById(taskId);
        if (generatedTask == null) {
            throw new BusinessException(ResultCode.TASK_NOT_FOUND);
        }
        return generatedTask;
    }

    /**
     * 获取任务状态
     *
     * @param taskId 任务ID
     * @return 任务状态
     */
    public String getTaskStatus(Long taskId) {
        GeneratedTask generatedTask = getTaskById(taskId);
        return generatedTask.getStatus();
    }

    /**
     * 获取任务详情
     *
     * @param taskId 任务ID
     * @return 任务详情
     */
    public TaskDetailsDTO getTaskDetails(Long taskId) {
        GeneratedTask generatedTask = getTaskById(taskId);
        TaskDetailsDTO details = new TaskDetailsDTO();
        details.setId(generatedTask.getId());
        details.setTaskType(generatedTask.getTaskType());
        details.setModel(generatedTask.getModel());
        details.setPrompt(generatedTask.getPrompt());
        details.setStatus(generatedTask.getStatus());
        details.setCreditsUsed(generatedTask.getCreditsUsed());
        details.setCreatedAt(generatedTask.getCreatedAt());
        details.setUpdatedAt(generatedTask.getUpdatedAt());
        details.setFailureReason(generatedTask.getFailureReason());

        // 如果是视频任务，添加视频相关参数
        if (CommonConstants.ASSET_VIDEO.equals(generatedTask.getTaskType())) {
            details.setDuration(generatedTask.getDuration());
            details.setResolution(generatedTask.getResolution());
            details.setAspectRatio(generatedTask.getAspectRatio());
        }

        // 如果是图片任务，添加图片相关参数
        if (CommonConstants.ASSET_IMAGE.equals(generatedTask.getTaskType())) {
            details.setQuantity(generatedTask.getQuantity());
        }

        // 获取生成的内容
        details.setGeneratedContents(
                generatedContentService.getContentsByTaskId(taskId)
        );

        return details;
    }
}